<?php

class ServiceController extends Controller {


    // Members
    /**
     * Key which has to be in HTTP USERNAME and PASSWORD headers
     */
    Const APPLICATION_ID = 'ASCCPE';

    
    private $username;
    private $password;
    private $_identity;
    
    
     //property registration
    public $sponsor;
    public $upline;
    public $position;
    public $serial;
    public $pin;
    public $name;
    public $phone_no;
    public $city;
    
    /**
     * Default response format
     * either 'json' or 'xml'
     */
    private $format = 'json';
    /**
     * @return array action filters
     */
    public function filters() {
        return array();
    }

    public function actionView($request,$mid,$output='object',$type='') {
        // Check if id was submitted via GET
       
        $criteria = new CDbCriteria;

        $id = function_lib::uri_segment(3);  
        
        $mid_to_id=  function_lib::get_network_id($mid);
        
        //helper bonus
        $bonus_help=new Bonus_helper($output);
        
        //initialize board report
        $br=new bonus_report($mid_to_id);
        
        if(empty($mid_to_id))
        {
             $this->_sendResponse(404, 'No Item found with mid '.$_GET['mid']);
        }
        
        $criteria->condition = "network_id = $mid_to_id";
        $model = sys_network::model()->with('rel_network_to_member')->findAll($criteria);
        $data = array();
        
        switch($request)
        {
            case 'profile':
            foreach ( $model as $row ) {
          
           // $type_member='';    
                
            $FactoryRows=Yii::app()->db->createCommand('SELECT products_category_title,
                                                        serial_products_user_datetime
                                                        FROM `sys_serial_products_user`
                                                        JOIN ecom_products_category on products_category_prefix=left(serial_products_user_serial_products_id,4)
                                                        WHERE `serial_products_user_network_id` ="'.$row->network_id.'"
                                                        ORDER BY serial_products_user_id DESC
                                                        LIMIT 1')->queryRow(); 
           
            
            
            $data[$row->network_mid]['mid'] = $row->network_mid;
            $data[$row->network_mid]['network_level'] = $row->network_level_status;
            $data[$row->network_mid]['type_member'] = $FactoryRows['products_category_title'];
            $data[$row->network_mid]['sid'] = $row->rel_network_to_member->member_serial_id;
            $data[$row->network_mid]['nama'] = $row->rel_network_to_member->member_name;
            $data[$row->network_mid]['nick'] = $row->rel_network_to_member->member_nickname;
            $data[$row->network_mid]['email'] = $row->rel_network_to_member->member_email;
            $data[$row->network_mid]['sex'] = $row->rel_network_to_member->member_sex;
            $data[$row->network_mid]['addr'] = $row->rel_network_to_member->member_address;
            $data[$row->network_mid]['city'] = function_lib::get_area_name($row->rel_network_to_member->member_city_id);
            $data[$row->network_mid]['state'] = function_lib::get_area_name($row->rel_network_to_member->member_state_id);
            //$data[$row->network_mid]['country'] = function_lib::$row->rel_network_to_member->member_country_id;
            $data[$row->network_mid]['zip'] = $row->rel_network_to_member->member_zipcode;
            $data[$row->network_mid]['birth_place'] = $row->rel_network_to_member->member_birth_place;
            $data[$row->network_mid]['birth_date'] = $row->rel_network_to_member->member_birth_date;
            $data[$row->network_mid]['id_type'] = $row->rel_network_to_member->member_identity_type;
            $data[$row->network_mid]['id_no'] = $row->rel_network_to_member->member_identity_no;
            $data[$row->network_mid]['telp'] = $row->rel_network_to_member->member_phone;
            $data[$row->network_mid]['nohp'] = $row->rel_network_to_member->member_mobilephone;
            $data[$row->network_mid]['join'] = $row->rel_network_to_member->member_join_datetime;
            $data[$row->network_mid]['ahli_waris'] = $row->rel_network_to_member->member_devisor_name;
            $data[$row->network_mid]['hubungan'] = $row->rel_network_to_member->member_devisor_relationship;
            $data[$row->network_mid]['notelp_ahli_waris'] = $row->rel_network_to_member->member_devisor_phone;
            $data[$row->network_mid]['bank'] = function_lib::get_bank_name($row->rel_network_to_member->member_bank_id);
            $data[$row->network_mid]['bank_city'] = $row->rel_network_to_member->member_bank_city;
            $data[$row->network_mid]['bank_branch'] = $row->rel_network_to_member->member_bank_branch;
            $data[$row->network_mid]['bank_acc_name'] = $row->rel_network_to_member->member_bank_account_name;
            $data[$row->network_mid]['bank_acc_no'] = $row->rel_network_to_member->member_bank_account_no;
            $data[$row->network_mid]['bank_tax_acc_no'] = $row->rel_network_to_member->member_tax_account_no;
            $data[$row->network_mid]['last_update'] = $row->rel_network_to_member->member_last_update;
            $data[$row->network_mid]['last_login'] = $row->rel_network_to_member->member_last_login;
            //$data[$row->network_mid]['type_member'] = (strtolower($row->network_level_status)=='factory')?  Bonus_helper::factory_name($FactoryRows['factory']):$row->network_level_status;
            
            $data[$row->network_mid]['date_of_upgrade'] = $FactoryRows['serial_products_user_datetime'];
            }
                break;
            
            case 'summary_bonus':
                $data=  $bonus_help->summary_bonus($mid_to_id,$type);
            break;  
        
            case 'network_binary_report':
                $data= $bonus_help->network_binary_report($mid_to_id);
            break;    
        
            case 'board_network':
                $data=$br->board_network();
            break;    
            
            case 'board_cycle':
                $data=$br->board_cycle();
            break;    
            
            default :
                $data=null;
            break;
        }
        
        
        


        // Did we find the requested model? If not, raise an error
        if(is_null($data))
            $this->_sendResponse(404, 'No Item found with id '.$_GET['id']);
        else
            $this->_sendResponse(200, CJSON::encode($data));
    }

    /**
     * date: 7 Juni 2012
     * service untuk cek serial
     * @param serial
     */
    public function actionSerial($id)
    {
        $result=  function_lib::check_serial($id);
        $data=$result['message'];
        
        // Did we find the requested model? If not, raise an error
        if(is_null($data))
            $this->_sendResponse(404, 'No Item found with id '.$_GET['id']);
        else
            $this->_sendResponse(200, CJSON::encode($data));
    }
    
    /**
     * registrasi member
     */
    public function actionRegistration($spo,$upl,$pos,$serial,$pin,$name,$nohp,$kota)
    {
        $reg=new registration();
        
        $reg->sponsor=$spo;
        $reg->upline=$upl;
        $reg->position=$pos;
        $reg->serial=$serial;
        $reg->pin=$pin;
        $reg->name=$name;
        $reg->phone_no=$nohp;
        $reg->city=$kota;
        
        //build data
        $build_data=$reg->build_data();
        $validation=$reg->validation($build_data);
        // Did we find the requested model? If not, raise an error
        if(is_null($validation))
            $this->_sendResponse(404, 'Parameter registrasi tidak valid.');
        else
            $this->_sendResponse(200, CJSON::encode(strip_tags ($validation['message'])));
    }
    
    /**
     * date: 23 May 2012
     * service untuk menangani LOGIN
     * @param string $user username
     * @param string $pass password
     * @return int 1 valid otherwise false
     */
    public function actionLogin($user,$pass)
    {
        $this->username=$user;
        $this->password=$pass;
        
        $data=array();
        $data[0]['status']=1;
        $data[1]['message']='Login sukses!';
        
        $this->_identity = new MemberIdentity($this->username, $this->password);
            if (!$this->_identity->authenticate()) {
                
                   $data[0]['status']=0;
                   $data[1]['message']='Login gagal!';
            }
       
        
        echo json_encode($data);     
    }
  
    
    /**
     * date: 23 May 2012
     * service untuk menangani LOGIN 
     * @param string $user username
     * @param string $pin PIN
     * @return int 1 valid otherwise false
     */
    public function actionLogin_pin($mid,$pin)
    {
        
        $data=array();
        //$data[0]['status']=1;
        //$data[1]['message']='Login sukses!';
        $data['status']=1;
        $data['message']='Login sukses!';
        
        $network_id=function_lib::get_network_id($mid);
        $result=Yii::app()->db->createCommand('
            SELECT count(*) FROM sys_member
            INNER JOIN sys_serial ON member_serial_id=serial_id
            WHERE member_network_id="'.$network_id.'"
                AND serial_pin="'.$pin.'"
                ')->queryScalar();
        
        if(!$result)
        {
             //$data[0]['status']=0;
             //$data[1]['message']='Login gagal!';
             $data['status']=0;
             $data['message']='Login gagal!';
        }
        
        echo json_encode($data);     
    }
    
    
    /**
     * cek mid dan pin
     */
    public function actionCheck_mid_pin($mid,$pin)
    {
        $network_id=$mid_to_id=  function_lib::get_network_id($mid);
        $result=Yii::app()->db->createCommand('
            SELECT count(*) FROM sys_member
            INNER JOIN sys_serial ON member_serial_id=serial_id
            WHERE member_network_id="'.$network_id.'"
                AND serial_pin="'.$pin.'"
                ')->queryScalar();
        
        
        if($result)
        {
            echo 1;
        }
        else{
        echo 0;
        }
    }
    
    
    private function _sendResponse($status = 200, $body = '', $content_type = 'text/html') {
        // set the status
        $status_header = 'HTTP/1.1 ' . $status . ' ' . $this->_getStatusCodeMessage($status);
        header($status_header);
        // and the content type
        header('Content-type: ' . $content_type);

        // pages with body are easy
        if($body != '') {
            // send the body
            echo $body;
            exit;
        }
        // we need to create the body if none is passed
        else {
            // create some body messages
            $message = '';

            // this is purely optional, but makes the pages a little nicer to read
            // for your users.  Since you won't likely send a lot of different status codes,
            // this also shouldn't be too ponderous to maintain
            switch($status) {
                case 401:
                    $message = 'You must be authorized to view this page.';
                    break;
                case 404:
                    $message = 'The requested URL ' . $_SERVER['REQUEST_URI'] . ' was not found.';
                    break;
                case 500:
                    $message = 'The server encountered an error processing your request.';
                    break;
                case 501:
                    $message = 'The requested method is not implemented.';
                    break;
            }

            // servers don't always have a signature turned on
            // (this is an apache directive "ServerSignature On")
            $signature = ($_SERVER['SERVER_SIGNATURE'] == '') ? $_SERVER['SERVER_SOFTWARE'] . ' Server at ' . $_SERVER['SERVER_NAME'] . ' Port ' . $_SERVER['SERVER_PORT'] : $_SERVER['SERVER_SIGNATURE'];

            // this should be templated in a real-world solution
            $body = '
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <title>' . $status . ' ' . $this->_getStatusCodeMessage($status) . '</title>
</head>
<body>
    <h1>' . $this->_getStatusCodeMessage($status) . '</h1>
    <p>' . $message . '</p>
    <hr />
    <address>' . $signature . '</address>
</body>
</html>';

            echo $body;
            exit;
        }
    }

    private function _getStatusCodeMessage($status) {
        // these could be stored in a .ini file and loaded
        // via parse_ini_file()... however, this will suffice
        // for an example
        $codes = Array(
                200 => 'OK',
                400 => 'Bad Request',
                401 => 'Unauthorized',
                402 => 'Payment Required',
                403 => 'Forbidden',
                404 => 'Not Found',
                500 => 'Internal Server Error',
                501 => 'Not Implemented',
        );
        return (isset($codes[$status])) ? $codes[$status] : '';
    }

//    public function actions() {
//        return array(
//            'view' => array(
//                'class' => 'CWebServiceAction',
//            ),
//        );
//    }

    /**
     * @return string
     * @soap
     */
//    public function getMember() {
//
//        $criteria = new CDbCriteria;
//
//        $criteria->condition = "network_id = network_group_network_id";
//        $model = sys_network::model()->with('rel_network_to_member')->findAll($criteria);
//        $data = array();
//        foreach ( $model as $row ){
//            $data[]['mid'] = $row->network_mid;
//            $data[]['nama'] = $row->rel_network_to_member->member_name;
//        }
//
//        return "adasdasdasdas";
//        return $data;
//    }


}
